package com.imooc.bilibili.service.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.imooc.bilibili.domain.exception.ConditionException;

import java.util.Calendar;
import java.util.Date;

public class TokenUtil {

    private static final String  ISSUR = "发放者";

   public static String generateToken(Long userId) throws Exception {

       //获取加密算法
       Algorithm rsa256 = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
       Calendar calendar = Calendar.getInstance();
       calendar.setTime(new Date());
       calendar.add(Calendar.SECOND, 30);
       return JWT.create()
               .withKeyId(String.valueOf(userId))
               .withIssuer(ISSUR)
               .withExpiresAt(calendar.getTime())
               .sign(rsa256);
   }

   public static Long verifyToken(String token) {

       try {
           Algorithm rsa256 = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
           JWTVerifier jwtVerifier = JWT.require(rsa256).build();
           DecodedJWT jwt = jwtVerifier.verify(token);
           String userId = jwt.getKeyId();
           return Long.valueOf(userId);
       } catch (TokenExpiredException e) {
           throw new ConditionException("555", "token过期");
       } catch (Exception e) {
           throw new ConditionException("非法用户token!");
       }
   }

}
